import click
from flask.cli import with_appcontext

from app.models.roleModel import (
    METHOD_TO_FILTER,
    FilterChoices,
    Permission,
    RolePolicyFilter,
)
from app.models.userModel import User
from tools import db


@click.command(
    "role_filter",
    context_settings={"ignore_unknown_options": True},
    short_help="eg: flask role_filter -s allow zhangsan /v1/xxx GET,PUT",
)
@click.option(
    "-s",
    "--strategy",
    type=click.Choice(["allow", "disable"]),
    help="add增加策略、delete删除策略",
)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
@with_appcontext
def role_filter(strategy, args):

    if len(args) < 4:
        print("参数有误")

    username, url, methods = args[:3]

    _filter = [METHOD_TO_FILTER[item] for item in methods.split(",")]
    if len(_filter) == len(METHOD_TO_FILTER):
        _filter = [FilterChoices.ALL]

    user = User.query.filter_by(username=username).all()
    if not user:
        print("用户不存在")

    permission = Permission.query.filter(Permission.path == url).all()
    if len(permission) != 1:
        print(f"资源查询错误，{permission}")

    role_policy_filter = [
        RolePolicyFilter(
            user_id=user[0].id,
            permission_id=permission[0].id,
            filter=_f.value,
            strategy=strategy,
        )
        for _f in _filter
    ]

    with db.auto_commit():
        with db.session.begin(subtransactions=True):
            db.session.add_all(role_policy_filter)

    print("操作成功")
